package com.qf;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 测试ajax
 * @author 千锋健哥
 */
@WebServlet("/test")
public class TestAjaxServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 设置请求和响应编码
        req.setCharacterEncoding("utf-8");
        //resp.setContentType("text/html;charset=utf-8");
        //如果使用jquery, 响应数据应该设置为json格式
        resp.setContentType("text/json;charset=utf-8");

        //2. 获取ajax提交的参数数据
        String userName = req.getParameter("userName");

        //3. 对参数进行判断
        String  result = null;
        if ("admin".equals(userName) || "root".equals(userName)) {
            //用户名重复, 返回0
            result = "0";
        } else {
            //用户名不重复, 返回1
            result = "1";
        }

        //4. 返回结果, 通过响应的输出流, 原路将数据写回到页面中
        resp.getWriter().write(result);
    }

}
